import {Component, HostListener, OnDestroy, OnInit} from "@angular/core";
import {CommService} from "../comm-service";
import {MyhttpService} from "../myhttp.service";
import {LocalStorageService} from "../local-storage-service";

declare var $: any;
declare var AMap: any;

@Component({
  template: `
    <div class="title">
      <div class="title_text">{{comptitle}}</div>
    </div>
    <!-- <div class="portlet box blue"> -->
    <!-- <div class="portlet-title">
      <div class="caption">
        试卷包出入库统计
      </div>
    </div> -->
    <!-- <div class="portlet-body"> -->
    <div class="row">
      <form class="form-horizontal" role="form">
        <div class="col-lg-4">
          <div class="form-group">
            <label class="control-label col-lg-3">招办/考点：</label>
            <div class="col-lg-8">
              <input type="text" class="form-control"/>
            </div>
          </div>
        </div>
        <div class="col-lg-4">
          <div class="form-group">
            <label class="control-label col-lg-3">试卷包名称：</label>
            <div class="col-lg-8">
              <input type="text" class="form-control"/>
            </div>
          </div>
        </div>

        <div class="col-lg-1">
          <button type="button" class="btn blue" (click)="inittable_sjbcrk()">
            <i class="fa fa-search"></i> 搜索
          </button>
        </div>
        <div class="col-lg-1">
          <button type="button" class="btn blue" (click)="inittable_sjbcrk()">
            <i class="fa fa-share"></i> 导出
          </button>
        </div>
      </form>
    </div>
    <div class="row">
      <div class="col-lg-12">
        <!--<my-table [o]="table_sjbcrk"></my-table>-->
        <table id="table_sjbcrk"></table>
      </div>
    </div>
    <!-- </div> -->
    <!-- </div> -->
    <div class="modal fad" id="addressModal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel">
      <div class="modal-dialog smmodalwidth" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">地址</h4>
          </div>
          <div class="modal-body">
            <div id="mapdiv" class="mapdiv"></div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">关 闭</button>
          </div>
        </div>
      </div>
    </div>
    <div class="modal fad" id="xq_Modal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel">
      <div class="modal-dialog smmodalwidth" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">出入库试卷信息</h4>
          </div>
          <div class="modal-body">
            <div class="sjbssqkRoom iecrollkf chromescrollkf">
              <ul class="list-group" *ngIf="tlineDatas.length">
                <li class="list-group-item tlineitem" *ngFor="let item of tlineDatas;index as index">
                  <div class="pull-left circleroom">
                 <span [ngClass]="{'endcircle':item.status<0,'ingcircle':item.status==0,'circle':item.status>0}">
                   <i class="fa fa-circle"></i>
                 </span>
                    <div class="vertical_line"
                         [ngClass]="{'endvline':item.status<0,'ingvline':item.status==0,'vline':item.status>0}"></div>
                  </div>
                  <div class="pull-left tsitem">
                  <span *ngIf="item.zt==0"
                        style="display: inline-block;width: 100%;height: 100%;line-height: 30px; text-align: center; background-color: #2094F2;color: #ffffff">运送开始</span>
                    <span *ngIf="item.zt==-1"
                          style="display: inline-block;width: 100%;height: 100%;line-height: 30px; text-align:center; background-color: #FD5354;color: #ffffff">运送结束</span>
                  </div>
                  <div class="pull-left xxitem">
                    <span class="time">{{item.tline}}</span>
                    <span class="marker" *ngIf="item.marker_e">{{item.marker_b}}<span
                      style="color: #FE8564">出库</span>{{item.marker_e}}</span>
                    <span class="marker" *ngIf="!item.marker_e">{{item.marker_b}}<span
                      style="color: #6CBB70">入库</span></span>
                  </div>
                  <div class="clearfix"></div>
                </li>
              </ul>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">关 闭</button>
          </div>
        </div>
      </div>
    </div>
  `,
  styles: [
    ".title{width: 100%;height: auto;padding: 10px; border-bottom: 1px solid #ccc; color: rgb(138 143 151);margin-bottom: 15px;}",
    ".title>.title_text{height: 15px;line-height: 15px;font-size: 15px;  width: auto;border-left: 5px solid #1477F3;padding-left: 10px}",
    ".mapdiv{width: 100%;height:600px;}",
    ".sjbssqkRoom{width: calc(100% - 17px);margin-top: 10px;height:300px;overflow-y: auto}",
    ".tlineitem{border: none;padding: 0px;margin: 0px}",
    ".tlineitem>.circleroom{width:40px; height: 30px;text-align: center;position: relative;padding-top: 5.5px}",
    ".circleroom>.vertical_line{position: absolute;left: 19.5px;top: 0px;width: 1px;height: 30px;}",
    ".tlineitem>.tsitem{width: 80px;height: 30px;}",
    ".tlineitem>.xxitem{width: calc(100% - 120px);height: 30px;line-height: 30px}",
    ".xxitem>.time{display: inline-block;width: 150px;text-align: center}",
    ".xxitem>.marker{display: inline-block;width: auto;padding-left: 10px}",
    ".endcircle{color: #ADDFE6}",
    ".ingcircle{color:#F9332A }",
    ".circle{color: #39A1F4;}",
    ".endvline{background-color: #ADDFE6}",
    ".ingvline{background-color: #F9332A}",
    ".vline{background-color: #39A1F4}",
  ]
})
export class TjbbSjbcrktjZHComponent implements OnInit, OnDestroy {
  comptitle: string = "试卷包出入库统计";
  sysBase: string;
  s_obj: any = {
    ksjhbh: "",
    ksgljgid: "",

    crklx: "",
    kslx: "",
    kssj: "",
    jssj: ""
  };
  table_sjbcrk: any;
  nowaddressMarker: any;
  map: any;
  tlineDatas: any[] = [];


  /**
   * 出入库的表格
   */
  inittable_sjbcrk(): void {
    const that = this;

    $("#table_sjbcrk").bootstrapTable({
      sidePagination: "server",
      pageSize: 10,
      pageList: [10, 20, 30],
      // total: "totalRows",
      //rows: that.sjcrkList,
      data: [{
        xh: 1,
        zbmc: "武汉市招办",
        kdmc: "长虹中学",
        sjbmc: "长虹中学26日上午1-1",
        sjbzt: '保密室入库',
        dqdz: '湖北省武汉市洪山区和平街道仟籽国际幼儿园东方雅园',
        jwd: "114.398479/30.611247",
        bh: "20210204"
      }],
      columns: [{
        title: '序号',
        field: "xh"
      }, {
        title: "招办名称",
        field: "zbmc",
      }, {
        title: "考点名称",
        field: "kdmc",
      }, {
        title: "试卷包名称",
        field: "sjbmc",
      }, {
        title: "试卷包状态",
        field: "sjbzt",
      }, {
        title: "出入库地址",
        field: "dqdz",
      }, {
        title: "经纬度",
        field: "jwd",
        events: this.myevents,
        formatter: function (v) {
          return "<a class='getAddress' href='javascript:void(0)'>" + v + "</a>";
        }
      }, {
        title: "详情",
        field: "bh",
        events: this.myevents,
        formatter: function (v) {
          let str: string = "";
          str += "<button type='button' class='btn btn-xs btn-info xq_yjjy'><i class='fa fa-search'></i> 详情</button>";
          return str;
        }
      }]
    });

    this.table_sjbcrk = {
      tableid: "table_sjbcrk",
      // url: "sjgz/rwjh/cxsjcrklb",
      //reqobj: "",
      sidePagination: "server",
      pageSize: 10,
      pageList: [10, 20, 30],
      // total: "totalRows",
      //rows: that.sjcrkList,
      data: [{
        xh: 1,
        zbmc: "武汉市招办",
        kdmc: "长虹中学",
        sjbmc: "长虹中学26日上午1-1",
        sjbzt: '正常',
        dqdz: '',
        jwd: "",
        bh: "20210204"
      }],
      columns: [{
        title: '序号',
        field: "xh"
      }, {
        title: "招办名称",
        field: "zbmc",
      }, {
        title: "考点名称",
        field: "kdmc",
      }, {
        title: "试卷包名称",
        field: "sjbmc",
      }, {
        title: "试卷包状态",
        field: "sjbzt",
      }, {
        title: "当前地址",
        field: "dqdz",
      }, {
        title: "经纬度",
        field: "jwd",
      }, {
        title: "详情",
        field: "bh",
        events: this.myevents,
        formatter: function (v) {
          let str: string = "";
          str += "<button type='button' class='btn btn-xs btn-info xq_yjjy'><i class='fa fa-search'></i> 详情</button>";
          return str;
        }
      }]
    };
    if (this.sysBase == "61") {
      this.table_sjbcrk.pageSize = 50;
      this.table_sjbcrk.pageList = [50];
      this.table_sjbcrk.hiddenPageinfoLink = true;
      this.table_sjbcrk.paginationLoop = true;
      this.table_sjbcrk.paginationPreText = "<i class='fa fa-arrow-left'></i>上一页";
      this.table_sjbcrk.paginationNextText = "下一页<i class='fa fa-arrow-right'></i>";
      this.table_sjbcrk.height = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 240 - 50;
    } else {
      this.table_sjbcrk.height = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 240 - 50;
    }
  }

  @HostListener("window:myevents", ["$event"])
  myevents = {
    "click .getAddress": function (e, value, row, index) {
      if (value) {
        const jwd = value.split("/");
        this.nowaddressMarker.setPosition(jwd);
        this.map.setZoomAndCenter(10, jwd);
        $("#addressModal").modal({
          keyboard: true,
          backdrop: "static"
        });
      }
    }.bind(this),
    "click .xq_yjjy": function (e, value, row, index) {
      // 出入库试卷信息
      this.getData();
      $("#xq_Modal").modal({
        keyboard: true,
        backdrop: "static"
      });
    }.bind(this)
  }


  getData(): void {
    const hqkcgzjcxxList = [{
      kssj: "2020-12-24 13:20",
      action: "ck",
      cfd: "湖北省教育考试印务中心",
      mdd: "武汉市洪山区保密室",
      zt: 0,
      //jcxq: "试卷包从【湖北省教育考试印务中心】出库，送往【武汉市洪山区保密室】"
    }, {
      kssj: "2020-12-26 06:20",
      action: "ck",
      cfd: "武汉市洪山区保密室",
      mdd: "武汉市长虹中学",
      zt: 1
      //jcxq: "试卷包从【武汉市洪山区保密室】出库，送往【武汉市长虹中学】"
    }, {
      kssj: "2020-12-26 06:43",
      action: "rk",
      cfd: "",
      mdd: "武汉市长虹中学",
      zt: 1
      //jcxq: "试卷包在【武汉市长虹中学】入库"
    }, {
      kssj: "2020-12-26 18:00",
      action: "ck",
      cfd: "武汉市长虹中学",
      mdd: "洪山区保密室",
      zt: 1
      //jcxq: "试卷包从【武汉市长虹中学】出库，送往【洪山区保密室】"
    }, {
      kssj: "2020-12-26 18:23",
      action: "rk",
      cfd: "",
      mdd: "洪山区保密室",
      zt: 1
      //jcxq: "试卷包在【洪山区保密室】入库"
    }, {
      kssj: "2020-12-28 08:40",
      action: "ck",
      cfd: "武汉市洪山区保密室",
      mdd: "湖北省沙湖教育考试极低评卷中心",
      zt: 1
      //jcxq: "试卷包从【武汉市洪山区保密室】出库，送往【湖北省沙湖教育考试极低评卷中心】"
    }, {
      kssj: "2020-12-28 09:43",
      action: "rk",
      cfd: "",
      mdd: "湖北省沙湖教育考试基地评卷中心",
      zt: -1
      // jcxq: "试卷包在【湖北省沙湖教育考试基地评卷中心】入库"
    }];
    this.tlineDatas = hqkcgzjcxxList.map((item) => {
      const actionv = item.action; // ck  rk
      const cfdv = item.cfd;
      const mddv = item.mdd;
      let markerbv: string = "";
      let markerev: string = "";
      if (actionv == "ck") {
        markerbv = `试卷包从【${cfdv}】`;
        markerev = `，送往【${mddv}】`;
      } else if (actionv == "rk") {
        markerbv = `试卷包在【${mddv}】`;
      }
      return {
        tline: item.kssj,
        marker_b: markerbv,
        marker_e: markerev,
        status: 1, // 初始化都是将来时
        zt: item.zt
      }
    });
    this.tlineDatas = this.tlineDatas.reverse();
    this.handerLine();
  }

  /**
   * status
   * -1  ---过去时 --灰
   * 0  --进行时 ---红
   * 1----将来时 ---蓝
   */
  handerLine(): void {
    if (!this.tlineDatas.length) {
      return
    }
    const nowms = Date.now(); //ms
    const data_mintime = this.tlineDatas[this.tlineDatas.length - 1]["tline"]; // 倒序
    const data_maxtime = this.tlineDatas[0]["tline"];
    const data_minms = this.commservice.convertTimeToInt(data_mintime);  // ms
    const data_maxms = this.commservice.convertTimeToInt(data_maxtime); // ms
    if (nowms < data_minms) {
      // -无穷  data_minms）
      this.tlineDatas.forEach((item) => {
        item.status = 1; // 都在将来时
      });
      this.tlineDatas[this.tlineDatas.length - 1]["status"] = 0;
    } else if (nowms < data_maxms) {
      // 【data_minms  data_maxms)
      let nowindex: number;
      this.tlineDatas.forEach((item, index) => {
        const ittlinev = item.tline;
        const itlinems = this.commservice.convertTimeToInt(ittlinev); // ms
        const itprelienms = this.tlineDatas[index - 1] ? this.commservice.convertTimeToInt(this.tlineDatas[index - 1]["tline"]) : 0;
        if (nowms == itlinems) {
          nowindex = index;
          item["tline"] = 0;
          for (let i = 0; i < nowindex; i++) {
            this.tlineDatas[i]["tline"] = 1;
          }
          for (let j = (nowindex + 1); j < this.tlineDatas.length; j++) {
            this.tlineDatas[j]["tline"] = -1;
          }
        }
        if (nowms > itlinems && nowms < itprelienms) {
          for (let i = 0; i < nowindex; i++) {
            this.tlineDatas[i]["tline"] = 1;
          }
          for (let j = nowindex; j < this.tlineDatas.length; j++) {
            this.tlineDatas[j]["tline"] = -1;
          }
        }
      });
    } else {
      //【data_maxms +无穷
      this.tlineDatas.forEach((item) => {
        item.status = -1;
      });
      this.tlineDatas[0]["status"] = 0;
    }
  }

  /**
   * 处理搜索表格
   */
  createSearchForm(): void {
    $('.datetimepickerB_content').datetimepicker({
      autoclose: true,
      language: 'zh-CN',
      format: 'yyyy-mm-dd hh:ii:ss',
      pickerPosition: "bottom-left",
      minView: 0
    }).on("changeDate", function (ev) {
      const selectdate = ev.date.valueOf(); // 实际时间+ 8h
      // 结束时间不能小于开始时间,
      $(".datetimepickerE_content").datetimepicker("setStartDate", new Date(selectdate - 8 * 60 * 60 * 1000));
    });
    $('.datetimepickerE_content').datetimepicker({
      autoclose: true,
      language: 'zh-CN',
      format: 'yyyy-mm-dd hh:ii:ss',
      pickerPosition: "bottom-left",
      minView: 0
    }).on("changeDate", function (ev) {
      const selectdate = ev.date.valueOf(); // 实际时间+ 8h
      // 开始时间不能大于结束时间
      $(".datetimepickerB_content").datetimepicker("setEndDate", new Date(selectdate - 8 * 60 * 60 * 1000));
    });
    const initBdate = this.commservice.YMDHMS_get(Date.now() - 8 * 60 * 60 * 1000);
    const initEdate = this.commservice.YMDHMS_get(false);
    this.s_obj.kssj = initBdate;
    this.s_obj.jssj = initEdate;
  }

  initMap(): void {
    const that = this;
    this.map = new AMap.Map("mapdiv", {
      resizeEnable: true, //是否监控地图容器尺寸变化，默认值为false
      zoom: 11, //地图显示的缩放级别，若center与level未赋值，地图初始化默认显示用户所在城市范围，没有center（中心点）和level ，所以这个暂时无效
    });
    this.nowaddressMarker = new AMap.Marker({
      map: that.map,
      //position: markobj.position,
      offset: new AMap.Pixel(-17, -14),
      //angle: Number(markobj.fxj) + 90 + 180,
      zIndex: 100,  //默认值是100
    });
    // AMap.plugin(['AMap.Geocoder'],
    //   function () {
    //     that.geocoder = new AMap.Geocoder({
    //       radius: 1000,
    //       extensions: "all"
    //     });
    //   });
  }

  // getAddresss(lnglatXY: any, callback: Function): void {
  //   this.geocoder.getAddress(lnglatXY, function (status, result) {
  //     if (status === 'complete' && result.info === 'OK') {
  //       callback(result);
  //     }
  //   });
  // }

  constructor(private commservice: CommService,
              private itservice: MyhttpService,
              private localStorageService: LocalStorageService) {

  }

  ngOnInit() {
    this.s_obj.ksjhbh = this.localStorageService.get("hksjh");
    this.initMap();
    this.createSearchForm();
    this.commservice.getSysmsg2((resp) => {
      this.sysBase = resp.sysBase;
      this.inittable_sjbcrk();
    });
  }

  ngOnDestroy() {

  }

}
